import router from '@/router'
import { useUserStoreHook } from '@/store/modules/user'
import { usePermissionStoreHook } from '@/store/modules/permission'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({ showSpinner: false }) // 进度条

const permissionStore = usePermissionStoreHook()

// 白名单路由
const whiteList = ['/login']

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const hasToken = localStorage.getItem('accessToken')
  if (hasToken) {
    if (to.path === '/login') {
      // 如果已登录，跳转首页
      next({ path: '/' })
      NProgress.done()
    } else {
      const userStore = useUserStoreHook()
      const hasRoles =
        userStore.user.roleNames && userStore.user.roleNames.length > 0
      if (hasRoles && userStore.user.id) {
        // 有用户信息和角色
        next()
      } else {
        Promise.all([
          await userStore.getUserInfo(),
          await permissionStore.generateRoutes(),
        ])
          .then(() => {
            next()
          })
          .catch(async () => {
            // 移除 token 并跳转登录页
            await userStore.resetStore()
            next(`/login?redirect=${to.path}`)
            NProgress.done()
          })
      }
    }
  } else {
    // 未登录可以访问白名单页面
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
